; Copyright 2013 padnest@gmail.com

; Licensed under the Apache License, Version 2.0 (the "License");
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
;   http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.

	list	 p=16f84A, R=DEC

	#include	p16f84A.inc
	#include	"macros.inc"

	__config	_HS_OSC & _PWRTE_ON & _WDT_OFF & _CP_OFF

#define PWM_CH0		PORTB, 0
#define PWM_CH1		PORTB, 1
#define PWM_CH2		PORTB, 2
#define PWM_CH3		PORTB, 3
#define PWM_CH4		PORTB, 4
#define PWM_CH5		PORTB, 5
#define PWM_CH6		PORTB, 6
#define PWM_CH7		PORTB, 7

	org 0xC0
ISR_W		res 1		; reserved to interrupt service routine (bank0 and bank1)
ISR_STATUS	res 1		; reserved to interrupt handler (bank0)

PWM_REG		res 8		; 8 PWM value registers
PWM_COUNT	res 1		; common PWM counter

COUNTER		res 1		; counter decremented every PWM reset event

RNDH    	res 1		; random 16 bit
RNDL    	res 1

XREG		res 1		; temp reg used in subroutines
YREG		res 1		; temp reg used in subroutines

	org			0x0000
	goto		main

	org			0x0004
	#include	"interrupts.inc"


main

	bank0
	clrf	PORTB					; clear PORTB (pwm channels)

	movlf	0x80, PWM_COUNT			; init pwm counter
	mov16lf	0xACE1, RNDH, RNDL		; init random generator
	clrf	COUNTER					; init COUNTER register

	bank1
	clrf	TRISB				; PORTB pin all output (pwm channels)

	movlw	b'10001000'			; PORTB pullup disabled, TMR0 internal clock no prescaler (4MHZ/4 = 1MHZ = 1uSec per increment)
	movwf	OPTION_REG			; RBPU<7> INTEDG<6> T0CS<5> T0SE<4> PSA<3> PS2<2> PS1<1> PS0<0>

	movlw	b'10100000'			; Global interrupt enabled, TMR0 interrupt enabled, TMRO interrupt flag cleared
	movwf	INTCON				; GIE<7> EEIE<6> T0IE<5> INTE<4> RBIE<3> T0IF<2> INTF<1> RBIF<0>

forever
	movf	COUNTER, F				; if COUNTER = 0
	btfss	STATUS, Z
	goto	forever

	call	sr_loadPwmRegisters		; load rnd values in PWM registers

	movlf	10, COUNTER				; restore COUNTER initial value
	goto	forever

	#include	"subs.inc"

	END